using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 碰撞层管理器
/// </summary>
public class CollisionManager : Singleton<CollisionManager>
{
    /// <summary>
    /// 存储物理层 由外到内排序
    /// </summary>
    [HideInInspector]public CollisionPrefab[] collisions;

    // // Start is called before the first frame update
    // void Start()
    // {
    //     Init();
    // }
    
    private GameObject collisionPrefab;

    // public void Pause(bool value)
    // {
    //     for (int i = 0; i < collisions.Length; i++)
    //     {
    //         collisions[i].canRotation = value;
    //     }
    // }

    /// <summary>
    /// 初始化CollisionManager 计算得到层级信息
    /// </summary>
    public void Init()
    {
        if (collisionPrefab == null)
        {
            collisionPrefab = Resources.Load<GameObject>("Prefabs/CollisonPrefab");
        }
        
        print("碰撞层" + transform.position);
        // 2.实例化碰撞层
        CollisonData[] datas = GameModel.Instance.collisonDatas;
        collisions = new CollisionPrefab[datas.Length];
        for (int i = 0; i < datas.Length; i++)
        {
            GameObject prefabGo = Instantiate(collisionPrefab, this.transform);
            CollisionPrefab prefab = prefabGo.GetComponent<CollisionPrefab>();
            collisions[i] = prefab;
            prefab.SetData(datas[i]);
        }
        CalculateHierarchy();
    }

    /// <summary>
    /// 计算物理层级，排序
    /// 使得由外到内排序
    /// </summary>
    private void CalculateHierarchy()
    {
        CollisionPrefab collision = null;
        for (int i = 0; i < collisions.Length; i++)
        {
            print(collisions[i].height);
        }
        // 数据量比较少 就使用冒泡了
        for (int i = 0; i < collisions.Length; i++)
        {
            for (int j = 0; j < collisions.Length - i - 1; j++)
            {
                if (collisions[j].height < collisions[j + 1].height)
                {
                    collision = collisions[j];
                    collisions[j] = collisions[j + 1];
                    collisions[j + 1] = collision;
                }
            }
        }
        for (int i = 0;i < collisions.Length;i++)
        {
            print(collisions[i].gameObject.name);
        }
        print("排序完成");
    }
}